<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class GiftPearl extends Base
{
    public $table = 'gift_pearl_library';
    protected $giftPearlStreamTable = 'gift_pearl_stream';

    private $redisKeyGiftPearlRank = 'GIFT:PEARL_RANK';
    private $redisKeyPearlGift = 'CACHE:PEARL_GIFT';
    private $redisKeyGiftPearlAnimateResources = "CACHE:GIFT:PEARL_ANIMATE_RESOURCES";

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 礼物列表
     * */
    public function giftList($condition, $page, $limit)
    {
        // 总条数
        $totalCount = DB::table($this->table)
            ->where($condition)
            ->count('gift_id');

        $data = DB::table($this->table)
            ->where($condition)
            ->orderBy('gift_sort', 'asc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get(['gift_id', 'name', 'image', 'animate_resource','animate_resource_md5', 'price', 'is_show']);

        $data = self::objToArray($data);
        foreach ($data as $key => $value) {
            $data[$key]['image'] = getPicDomain() . $value['image'];

            if (empty($value['animate_resource'])) {
                $data[$key]['animate_resource'] = null;
            } else {
                $data[$key]['animate_resource'] = getPicDomain() . $value['animate_resource'];
            }
        }

        return $this->checkPageData($page, $limit, $totalCount, $data);
    }

    /**
     * 收到的礼物流水列表
     * */
    public function obtainGiftList($condition, $page, $limit)
    {
        foreach ($condition as $key => $value) {
            unset($condition[$key]);
            $condition[$this->giftPearlStreamTable . '.' . $key] = $value;
        }

        // 总条数
        $totalCount = DB::table($this->giftPearlStreamTable)
            ->where($condition)
            ->sum('gift_num');

        $data = DB::table($this->giftPearlStreamTable)
            ->where($condition)
            ->leftJoin('user', $this->giftPearlStreamTable . '.from_user_id', '=', 'user.user_id')
            ->orderBy($this->giftPearlStreamTable . '.gift_price', 'desc')
            ->groupBy('gift_id')
            ->select('gift_id', 'gift_name as name', 'gift_price as price', 'gift_image as image', DB::raw('sum(gift_num) as total_num'))
            // ->select($this->giftPearlStreamTable . '.gift_id', $this->giftPearlStreamTable . '.gift_name as name', $this->giftPearlStreamTable . '.gift_price as price', $this->giftPearlStreamTable . '.gift_image as image', $this->giftPearlStreamTable . '.gift_num', 'user.nickname as from_user_nickname')// , DB::raw('sum(gift_num) as total_num')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();

        $data = self::objToArray($data);
        foreach ($data as $key => $value) {
            $data[$key]['image'] = getPicDomain() . $value['image'];
            $data[$key]['total_num'] = intval($value['total_num']);
        }

        return $this->checkPageData($page, $limit, $totalCount, self::objToArray($data));
    }

    /**
     * 获取礼物
     * @param $giftId
     * @return mixed
     */
    public function getGift($giftId)
    {
        $data = Redis::HGET($this->redisKeyPearlGift, $giftId);
        if (!empty($data)) {
            return json_decode($data, true);
        }
        $res = DB::table($this->table)
            ->where(['gift_id' => $giftId])
            ->first(['gift_id', 'name', 'image', 'animate_resource', 'price']);
        $result = self::objToArray($res);
        if (empty($result['animate_resource'])) {
            $result['animate_resource'] = null;
        } else {
            $result['animate_resource'] = getPicDomain() . $result['animate_resource'];
        }
        $result['image'] = getPicDomain() . $result['image'];
        Redis::HSET($this->redisKeyPearlGift, $giftId, json_encode($result));
        if (Redis::TTL($this->redisKeyPearlGift) == -1) {
            Redis::EXPIRE($this->redisKeyPearlGift, 60 * 5);
        }
        return $result;
    }

    /**
     * 获取预加载资源列表
     * @return array
     */
    public function getAnimateResources()
    {
        $data = Redis::GET($this->redisKeyGiftPearlAnimateResources);
        if (!empty($data)) {
            return json_decode($data, true);
        }

        $res = DB::table($this->table)->get(['gift_id', 'animate_resource','animate_resource_md5']);
        $result = self::objToArray($res);
        $data = [];
        for ($i = 0; $i < count($result); $i++) {
            if (!empty($result[$i]['animate_resource'])) {
                $result[$i]['animate_resource'] = getPicDomain() . $result[$i]['animate_resource'];
                $data[] = $result[$i];
            }
        }

        Redis::SET($this->redisKeyGiftPearlAnimateResources, json_encode($data));
        Redis::EXPIRE($this->redisKeyGiftPearlAnimateResources, 3600);

        return $data;
    }

    /**
     * 更新排行榜（忽略-统一使用Model/Gift.php内方法）
     * */
    public function updateRank($fromUserId, $toUserId, $giftId, $giftNum)
    {
        Redis::ZADD($this->redisKeyGiftPearlRank, time(), sprintf("%d|%d|%d|%d", $fromUserId, $toUserId, $giftId, $giftNum));
        Redis::ZREMRANGEBYRANK($this->redisKeyGiftPearlRank, 0, -201);
    }

    /**
     * 获取礼物排行榜（忽略-统一使用Model/Gift.php内方法）
     */
    public function getRank($page, $limit)
    {
        $data = [];

        // 总条数
        $totalCount = Redis::zcard($this->redisKeyGiftPearlRank);

        // 开始-结束 范围取值
        $start = $limit * $page;
        $end = $start + $limit - 1;

        $ret = Redis::zrevrange($this->redisKeyGiftPearlRank, $start, $end);
        foreach ($ret as $item) {
            $itemData = explode('|', $item);
            $data[] = [
                'from_user_id' => intval($itemData[0]),
                'to_user_id' => intval($itemData[1]),
                'gift_id' => intval($itemData[2]),
                'gift_num' => intval($itemData[3])
            ];
        }

        return $this->checkPageData($page, $limit, $totalCount, $data);
    }

    /**
     * 获取房间礼物流水
     * @param $room_id
     * @return mixed
     */
    public function roomStream($condition, $page, $limit)
    {
        // 总条数
        $totalCount = DB::table($this->giftPearlStreamTable)
            ->where($condition)
            ->count('gift_id');

        $data = DB::table($this->giftPearlStreamTable)
            ->where($condition)
            ->offset($page * $limit)
            ->limit($limit)
            ->orderByDesc('change_timestamp')
            ->get(['user_id', 'from_user_id', 'gift_id', 'gift_name', 'gift_price', 'gift_num', 'gift_image', 'gift_animate_resource', 'change_timestamp as timestamp', 'type']);

        return $this->checkPageData($page, $limit, $totalCount, self::objToArray($data));
    }

    /**
     * 批量写入礼物流水
     * */
    public function insertBatch($data)
    {
        $this->table = $this->giftPearlStreamTable;
        return parent::insertBatch($data); // TODO: Change the autogenerated stub
    }


    public function getAll()
    {
        $data = DB::table($this->table)
            ->get(['gift_id', 'name', 'image', 'animate_resource','animate_resource_md5', 'price', 'is_show', 'ext_data','gift_label_id']);

        $data = self::objToArray($data);
        foreach ($data as $key => $value) {
            $data[$key]['image'] = getPicDomain() . $value['image'];

            if (empty($value['animate_resource'])) {
                $data[$key]['animate_resource'] = null;
            } else {
                $data[$key]['animate_resource'] = getPicDomain() . $value['animate_resource'];
            }
        }

        return $data;
    }

    public function getData()
    {
        $data = DB::table($this->table)
            ->get(['gift_id', 'name', 'image', 'animate_resource','animate_resource_md5', 'price', 'is_show']);
        $data = self::objToArray($data);
        $picDomain = getPicDomain();
        foreach($data as &$item) {
            $item['image'] = $picDomain.$item['image'];
            $item['animate_resource'] = $picDomain.$item['animate_resource'];
        }
        return $data;
    }

    public function getReceiveNum($userId){
        $condition = ['user_id' => $userId];
        return DB::table($this->giftPearlStreamTable)
            ->where($condition)
            ->where('change_timestamp', '<', 1577807999)
            ->sum("gift_num");
    }

    public function getSendGiftUserList($userId, $page = 0, $page_size = 1){
        $condition = ['from_user_id' => $userId];
        $document = DB::table($this->giftPearlStreamTable)
            ->where($condition)
            ->where('change_timestamp', '<', 1577807999)
            ->orderBy('total_num', 'desc')
            ->groupBy('user_id')
            ->select('user_id', DB::raw('sum(gift_num) as total_num'))
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get();

        return $result = self::objToArray($document);
    }
}